package com.eascs.placeonfile.task;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StopWatch;
import com.eascs.placeonfile.service.O2oFileService;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Component("taskJob")
public class O2oStartUpOnFile {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	O2oFileService fileService;
	@Reference
	WorkFlowService workFlowService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Scheduled(cron = "0 0/120 *  * * ? ")
	public void startUp() {
		logger.debug("启动归档任务任务开始");
		StopWatch stopWatch = new StopWatch();
		List<O2oLoanapplyEntity> loans = fileService.getLoans();
		if(null!=loans&&loans.size()>0){
			for (int i = 0; i < loans.size(); i++) {
				this.startUp(loans.get(i).getLoanapplyNo());
			}
		}
		logger.debug("生成日报表任务结束，共耗时：[{}]分", stopWatch.elapsedTime() / 1000 / 60);
	}
	
	public void startUp(String loanapplyNo){
		O2oLoanapplyEntity loan = o2oLoanapplyService.findById(loanapplyNo);
		WFRequestParam param = new WFRequestParam();
		param.setReferId(loan.getLoanapplyNo());
		param.setReferCode(loan.getBillCode());
		param.setReferUrl("http://xxxx.eascs.com/getDetail");
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType(String.valueOf(ProcessTemplate.PROECESS_TYPE_PLACE_ON_FILE));
		param.setProcessVersion("v1");
		param.setAppliedby(loan.getOperatorNo());
		param.setAppliedbyName(loan.getOperatorName());
		param.setOrgNo(loan.getLtd());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess()) {
			o2oLoanapplyService.updateOnfileStatus(StatusContexts.O2O_YES, loan.getLoanapplyNo());
		} else {
			logger.error("启动归档失败，错误信息", modelResult.getDetailStack());
		}
	}
}
